import {
    createCtxMenuConfig,
    MenuItemType,
    IconStore,
    XFlowNodeCommands,
    XFlowEdgeCommands,
    MODELS,
} from '@antv/xflow'
import { DeleteOutlined, EditOutlined, StopOutlined, UnorderedListOutlined } from '@ant-design/icons'
import * as service from './service'

import type {
    IGraphCommand,
    NsNodeCmd,
    NsEdgeCmd,
    IMenuOptions,
    NsGraph,
    IArgsBase,
    HookHub,
    ICmdHooks as IHooks,
} from '@antv/xflow'
import type { ContextMenuInfo } from '@/types/flow'

interface INode extends NsGraph.INodeConfig {
    menuItems: string[]
}

/** 节点命令 */
const category = '节点操作'
/** 清除画布 */
export const CLEAR_GRAPH: IGraphCommand = {
    id: 'xflow:clear-graph',
    label: '清除',
    category,
}
/** 导出 */
export const EXPORT_GRAPH: IGraphCommand = {
    id: 'xflow:export-graph',
    label: '导出',
    category,
}
/** 重命名节点弹窗 */
export const SHOW_RENAME_MODAL: IGraphCommand = {
    id: 'xflow:rename-node-modal',
    label: '打开重命名弹窗',
    category,
}
/** Command: 用于注册named factory */
export const command = SHOW_RENAME_MODAL
/** hook name */
export const hookKey = 'renameNode'
/** hook 参数类型 */
export interface IArgs extends IArgsBase {
    nodeConfig: NsGraph.INodeConfig
    updateNodeNameService: IUpdateNodeNameService
}
export interface IUpdateNodeNameService {
    (newName: string, nodeConfig: NsGraph.INodeConfig, meta: NsGraph.IGraphMeta): Promise<{
        err: string | null
        nodeName: string
    }>
}
/** hook handler 返回类型 */
export interface IResult {
    err: string | null
    preNodeName?: string
    currentNodeName?: string
}
/** hooks 类型 */
export interface ICmdHooks extends IHooks {
    renameNode: HookHub<IArgs, IResult>
}

console.log('菜单的id合集');
console.log(`删除边id`, XFlowEdgeCommands.DEL_EDGE.id);
console.log(`删除节点id`, XFlowNodeCommands.DEL_NODE.id);

/** menuitem 配置 */
/** 注册菜单依赖的icon */
IconStore.set('DeleteOutlined', DeleteOutlined)
IconStore.set('EditOutlined', EditOutlined)
IconStore.set('StopOutlined', StopOutlined)
IconStore.set('UnorderedListOutlined', UnorderedListOutlined)

export const getDynamicMenuItems = (state: MODELS.CONTEXTMENU_TARGET.IState) => {
    const data = state?.cell?.getData<INode>()
    return {
        id: '动态渲的submenu',
        label: '动态渲染的菜单',
        iconName: 'UnorderedListOutlined',
        type: MenuItemType.Submenu,
        submenu: data?.menuItems?.map((item, idx) => {
            return {
                id: item + '#' + idx,
                label: item + '#' + (idx + 1),
                type: MenuItemType.Leaf,
                iconName: 'UnorderedListOutlined',
                onClick: async ({ target }) => {
                    console.log('点击子菜单', target, item)
                },
            }
        }),
        onClick: async ({ target }) => {
            console.log('动态渲染的菜单被点击', target);
        },
    } as IMenuOptions
}

/** 边菜单 */
export const DELETE_EDGE: IMenuOptions = {
    id: XFlowEdgeCommands.DEL_EDGE.id,
    label: '删除边',
    iconName: 'DeleteOutlined',
    onClick: async ({ target, commandService }) => {
        commandService.executeCommand<NsEdgeCmd.DelEdge.IArgs>(
            XFlowEdgeCommands.DEL_EDGE.id,
            {
                edgeConfig: target.data as NsGraph.IEdgeConfig,
            }
        )
    },
}

/** 节点菜单 */
export const DELETE_NODE: IMenuOptions = {
    id: XFlowNodeCommands.DEL_NODE.id,
    label: '删除节点',
    iconName: 'DeleteOutlined',
    onClick: async ({ target, commandService }) => {
        commandService.executeCommand<NsNodeCmd.DelNode.IArgs>(
            XFlowNodeCommands.DEL_NODE.id,
            {
                nodeConfig: { id: target?.data?.id as string },
            }
        )
    },
}

/** 
 * 画布菜单
 * 默认菜单
 *  */
export const EMPTY_MENU: IMenuOptions = {
    id: 'EMPTY_MENU_ITEM',
    label: '暂无可用',
    isEnabled: false,
    iconName: 'DeleteOutlined',
}

/** 分割线 */
export const SEPARATOR: IMenuOptions = {
    id: 'separator',
    type: MenuItemType.Separator,
}

const NODE_LINK: IMenuOptions = {
    id: 'NODE_LINK',
    label: 'NODE_LINK',
    render: ({ children }) => {
        return (
            <a
                rel="noreferrer"
                target="_blank"
                href="https://baidu.com"
                style={{ padding: '0 16px' }}
            >
                一个自定义渲染的连接
            </a>
        )
    },
}

export const useMenuConfig = createCtxMenuConfig(config => {
    config.setMenuModelService(async (target, model, modelService, toDispose) => {
        const { type, cell } = target as ContextMenuInfo
        console.log('菜单：', type, cell, modelService, toDispose)
        switch (type) {
            /** 节点菜单 */
            case 'node':
                model.setValue({
                    id: 'root',
                    type: MenuItemType.Root,
                    submenu: [
                        DELETE_NODE,
                        getDynamicMenuItems(target),
                        SEPARATOR,
                        NODE_LINK,
                    ],
                })
                break
            /** 边菜单 */
            case 'edge':
                model.setValue({
                    id: 'root',
                    type: MenuItemType.Root,
                    submenu: [DELETE_EDGE],
                })
                break
            /** 画布菜单 */
            case 'blank':
                model.setValue({
                    id: 'root',
                    type: MenuItemType.Root,
                    submenu: [EMPTY_MENU],
                })
                break
            /** 默认菜单 */
            default:
                model.setValue({
                    id: 'root',
                    type: MenuItemType.Root,
                    submenu: [EMPTY_MENU],
                })
                break
        }
    })
})